#include "enesim_bench_common.h"
#include "Equanime.h"

static Equanime *eq;
static Equ_Layer *layer;
static Equ_Surface *surface;
static Enesim_Buffer *output;

static Enesim_Buffer_Format _equanime_format_to_enesim(Equ_Format fmt)
{
	switch (fmt)
	{
		case EQU_FORMAT_ARGB8888:
		return ENESIM_CONVERTER_ARGB8888;
		break;

		case EQU_FORMAT_RGB888:
		return ENESIM_CONVERTER_RGB888;
		break;

		default:
		break;
	}
}

static void _equanime_enesim_data_set(Equ_Surface_Data *sdata, size_t pitch, Enesim_Buffer_Sw_Data *bdata)
{
	switch (sdata->fmt)
	{
		case EQU_FORMAT_ARGB8888:
		bdata->argb8888.plane0 = sdata->data.argb8888.plane0;
		bdata->argb8888.plane0_stride = pitch;
		break;

		case EQU_FORMAT_RGB888:
		bdata->rgb888.plane0 = sdata->data.rgb888.plane0;
		bdata->rgb888.plane0_stride = pitch;
		break;
	}
}

static void _display(void *data, Enesim_Surface *s, const char *name)
{
	Eina_Rectangle rect;

	eina_rectangle_coords_from(&rect, 0, 0, opt_width, opt_height);
	/* convert the surface to the destination format */
	enesim_converter_surface(s, output, ENESIM_ANGLE_0, &rect, 0, 0);
	/* put it on the layer */
	equ_layer_surface_put(eq, layer, surface, 0, 0, &rect);
	equ_sync(eq);
}

static void _sync(void *data, Enesim_Surface *s)
{

}

static void * _init(void)
{
	Equ_Host *host;
	Equ_Controller *c;
	Equ_Layer_Status status;
	Eina_Rectangle rect;
	Equ_Surface_Data data;
	Enesim_Buffer_Sw_Data bdata;
	int w, h;
	size_t pitch;

	equ_init();
	eq = equ_new(0xea);
	if (!eq) goto err_equ;

	/* get the default host */
	host = equ_host_get(eq, NULL);
	if (!host)
	{
		printf("No hosts available\n");
		goto err_host;
	}
	/* get the default controller */
	c = equ_host_controller_get(eq, host, NULL);
	if (!c)
	{
		printf("No controller available\n");
		goto err_controller;
	}
	/* get the default layer */
	layer = equ_controller_layer_get(eq, c, NULL);
	if (!layer)
	{
		printf("No layer available\n");
		goto err_layer;
	}
	/* get the format of the layer */
	equ_layer_status_get(eq, layer, &status);
	/* get a surface */
	printf("%d %d\n", opt_width, opt_height);
	eina_rectangle_coords_from(&rect, 0, 0, opt_width, opt_height);
	surface = equ_host_surface_get(eq, host, rect.w, rect.h, status.fmt, EQU_SURFACE_SYSTEM);
	if (!surface)
	{
		printf("can not create the surface\n");
		goto err_surface;
	}
	/* create the output buffer from the surface */
	equ_surface_data_get(eq, surface, &data);
	equ_surface_size_get(eq, surface, &w, &h);
	pitch = equ_format_pitch_get(data.fmt, w);
	
	_equanime_enesim_data_set(&data, pitch, &bdata);
	output = enesim_buffer_new_data_from(ENESIM_BACKEND_SOFTWARE, _equanime_format_to_enesim(data.fmt), w, h, &bdata);

	return NULL;

err_surface:
err_layer:
err_controller:
err_host:
err_equ:
	exit(1);
}

static void _shutdown(void *data)
{
	equ_surface_delete(eq, surface);
	equ_shutdown();
}

Benchmark_Output output_equanime = {
	.display = _display,
	.init = _init,
	.shutdown = _shutdown,
};

